package servlet;

import bean.Student;
import dao.StudentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/query")
public class Query extends HttpServlet {
    private String name;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("Query-doGet...");
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.设置请求和响应的编码格式，以及响应的格式
        request.setCharacterEncoding("utf-8"); // 设置获取数据的格式

        // 2.获取请求的参数
        String name = request.getParameter("name"); //根据表单的name属性获取学生姓名
        System.out.println(name);

        // 3.执行业务处理
        StudentDao studentDao = new StudentDao();
        Student student = studentDao.student(name);

        // 4.判断信息是否为空
        if (student != null) {

            HttpSession session = request.getSession();
            session.setAttribute("student", student);

            // 搜索成功,当前servlet业务处理完毕
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else {
            // 搜索失败，传入错误信息并跳转页面
            request.setAttribute("error_msg","搜索失败！请重新输入name！");
        }
    }
}

